package gw.com.android.ui.news;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.utils.AppJsonUtil;
import gw.com.android.utils.ThreadPool;
import www.com.library.app.Logger;
import www.com.library.app.PushMsgTabFragment;
import www.com.library.model.DataItemDetail;
import www.com.library.util.NetworkMonitor;
import www.com.library.view.RecycleViewDivider;
import www.com.library.view.RecyclerClickListener;
import www.com.library.view.XRecyclerView;

/**
 * Created by reeta.zou on 2016/8/3.
 * 资讯子fragment
 */
public class NewsFragment extends PushMsgTabFragment implements XRecyclerView.LoadingListener{

    @BindView(R.id.list_view)
    XRecyclerView mListView;
    @BindView(R.id.empty_title)
    TextView mEmptyView;
    @BindView(R.id.error_layout)
    View mErrorView;

    private String mType;
    private String mTitle;
    private String key;
    private NewsItemAdapter mAdapter;
    private int defalutPage = 0;
    private int mCurPage = defalutPage;
    private int pageSize = 10;
    private int mTotalPage = 1;
    private Thread mThread;

    private boolean enablePullDown = true;// 允许下拉刷新， 当为FALSE时， 只下拉刷新一次
    private boolean enablePullUp = true;// 允许上拉,当为false时，隐藏footer

    public NewsFragment() {

    }

    public static NewsFragment newInstance(String type, String title, String key) {
        NewsFragment fragment = new NewsFragment();
        Bundle args = new Bundle();
        args.putString("type", type);
        args.putString("title", title);
        args.putString("key", key);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mType = getArguments().getString("type");
            mTitle = getArguments().getString("title");
            key = getArguments().getString("key");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return mRootView;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_news_item;
    }

    @Override
    protected void initLayoutView() {
        ButterKnife.bind(this, mRootView);
        // 设置布局管理器
        mListView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mListView.addItemDecoration(new RecycleViewDivider(
                getActivity(), LinearLayoutManager.VERTICAL));
        setEnablePull(enablePullUp, enablePullDown);
    }

    public void setEnablePull(boolean pullUp, boolean pullDown) {
        this.enablePullUp = pullUp;
        this.enablePullDown = pullDown;
        if(mListView != null) {
            if(!enablePullUp) {
                mListView.setLoadingMoreEnabled(false);
                mListView.hideFooter();
            }
        }

    }

    @Override
    protected void initViewData() {
        mAdapter = new NewsItemAdapter(getActivity(), mType, new RecyclerClickListener() {
            @Override
            public void onClick(int position, DataItemDetail itemDetail) {
                DataItemDetail item = mAdapter.getItem(position);
                AppTerminal.instance().setNewsMarkRead(AppContances.MARK_NEWS_TYPE, mType, item.getInt("id"));
                mAdapter.addMark(item.getInt("id"));
                if(mType.equals(AppContances.NEWS_TYPE_COLLECT+"")){
                    if(item.getString("key").equals(ConfigType.INSTANT_NEWS_TYPE)){
                        mTitle = AppMain.getAppString(R.string.instantNewsType);
                    }else{
                        mTitle = AppMain.getAppString(R.string.professionalType);
                    }
                }else{
                    item.setStringValue("key", key);
                }
                ActivityManager.showNewsDetailActivity(getActivity(), mTitle, item);
            }
        });
        mListView.setAdapter(mAdapter);
        mListView.setLoadingListener(this);
        mListView.setRefreshing(true);
        mListView.hideFooter();
    }

    /**
     * 加载数据
     */
    private void loadData(){
        ThreadPool.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                Logger.e("newsFragment线程id = " + android.os.Process.myTid());
                AppTerminal.instance().getNewsList(mType, pageSize, mCurPage);
            }
        });
    }

    @Override
    public void onRefresh() {
        Logger.e("onRefresh mType = " + mType);
        mCurPage = defalutPage;
        if(mType.equals(AppContances.NEWS_TYPE_COLLECT+"")){
            String result = AppTerminal.instance().getNewsInfo();
            loadFinish(0,result);
        }else{
            if(!NetworkMonitor.hasNetWorkNoToast()){
                onFail("");
                return;
            }
            mListView.resetNoMore(false);
            loadData();
        }
        if(!enablePullDown) {
            mListView.setPullRefreshEnabled(false);
        }
    }

    @Override
    public void onLoadMore() {
        Logger.e("onLoadMore mType = " + mType);
        if(!mType.equals(AppContances.NEWS_TYPE_COLLECT+"")){
            if(!NetworkMonitor.hasNetWork()){
                onFail("");
                return;
            }
            loadData();
        }
    }

    /**
     * 处理加载成功的数据
     * @param strObject
     */
    public void loadFinish(int ret, String strObject){
        Logger.e("资讯列表 loadFinish ret = " + ret);
        if (ret != 0) {
            onFail(ConfigUtil.instance().getErrorConfigObject().optString(ret+""));
        } else {
            try {
                if(strObject.contains("pages") && strObject.contains("total")){
                    JSONObject object = new JSONObject(strObject);
                    mTotalPage = object.optJSONObject("pages").optInt("total");
                }else{
                    mTotalPage = 1;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if(mCurPage == defalutPage){
                mAdapter.replaceData(AppJsonUtil.getNewsList(strObject));
                Logger.e("loadFinish onRefresh end mType = " + mType);
                mListView.refreshComplete();
                if(mType.equals(AppContances.NEWS_TYPE_COLLECT+"")){
                    if(mAdapter.getItemCount() < 1){
                        mEmptyView.setVisibility(View.VISIBLE);
                        mListView.setVisibility(View.GONE);
                    }
                }
            }else{
                mAdapter.addData(AppJsonUtil.getNewsList(strObject));
                mListView.loadMoreComplete();
                if(mCurPage >= mTotalPage){
                    mListView.setNoMore(true);
                }
                Logger.e("loadFinish onLoadMore end mType = " + mType+ " mCurPage = " + mCurPage);
            }
            if (mCurPage >= mTotalPage) {
                mListView.setNoMore(true);
            } else {
                mListView.setNoMore(false);
                mCurPage++;
            }
        }
    }

    /**
     * 处理失败情况
     * @param errorMessage
     */
    private void onFail(String errorMessage){
        if(mCurPage == defalutPage){
            Logger.e("onFail onRefresh end mType = " + mType);
            mListView.refreshComplete();
            mListView.setNoMore(false);
            mListView.setVisibility(View.GONE);
            if(null != mErrorView){
                mErrorView.setVisibility(View.VISIBLE);
            }
        }else{
            mListView.loadMoreComplete();
            mListView.setNoMore(true);
            Logger.e("onFail onLoadMore end mType = " + mType + " mCurPage = " + mCurPage);
        }
        if(isResumed() && isVisible() && getActivity() != null && !"".equals(errorMessage)){
            showToastPopWindow(errorMessage);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if(null != mAdapter){
            mAdapter.notifyDataSetChanged();
        }
        mListView.resetTimeZone();
    }

    @OnClick(R.id.error_layout)
    public void errorClick(){
        if(!NetworkMonitor.hasNetWork()){
            return;
        }
        if(null != mErrorView){
            mErrorView.setVisibility(View.GONE);
        }
        if(null != mListView){
            mListView.setVisibility(View.VISIBLE);
            mListView.hideFooter();
            mListView.setRefreshing(true);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden) {
            mListView.resetTimeZone();
        }
    }
}
